from flask import render_template, redirect, url_for, flash, request
from flask_login import current_user, login_required
from app import db
from app.users import bp
from app.users.forms import ProfileForm
from app.models import User, Skill

@bp.route('/')
@login_required
def index():
    users = User.query.all()
    return render_template('users/index.html', title='成员列表', users=users)

@bp.route('/<int:id>')
@login_required
def profile(id):
    user = User.query.get_or_404(id)
    return render_template('users/profile.html', title=f'{user.name}的个人档案', user=user)

@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = ProfileForm()
    # 获取所有技能标签供选择
    form.skills.choices = [(s.id, s.name) for s in Skill.query.all()]
    # 预选已关联的技能
    if request.method == 'GET':
        form.name.data = current_user.name
        form.skills.data = [s.id for s in current_user.skills]
    
    if form.validate_on_submit():
        current_user.name = form.name.data
        # 更新关联的技能标签
        selected_skills = Skill.query.filter(Skill.id.in_(form.skills.data)).all()
        current_user.skills = selected_skills
        
        db.session.commit()
        flash('个人档案已更新！')
        return redirect(url_for('users.profile', id=current_user.id))
    
    return render_template('users/edit_profile.html', title='编辑个人档案', form=form)